﻿using Map;
using Map_Creator.MapInfo;
using Microsoft.Xna.Framework;

namespace Map_Creator.RedoUndo.Actions
{
    class AutoTileChange : IAction
    {
        private AutoTileData newAutoTile;
        private int destTileSetID;
        private Point destPosition;
        private AutoTileData oldAutoTile;

        public AutoTileChange(AutoTileData newAutoTile, TileSet tileSet, Point destPosition)
        {
            this.newAutoTile = newAutoTile;
            destTileSetID = tileSet.ID;
            this.destPosition = destPosition;
            var oldTile = tileSet.DefinedAutoTiles[destPosition];
            if (oldTile == null) return;

            if (oldTile.Type == TileType.Auto4)
                oldAutoTile = ((AutoTile4)oldTile).AutoData;
            else if (oldTile.Type == TileType.AutoDP)
                oldAutoTile = ((AutoTile5)oldTile).AutoData;
        }

        public void Do()
        {
            var tileSet = ((TileSet)BaseObject.Objects[destTileSetID]);
            if (newAutoTile == null)
            {
                tileSet.DefinedAutoTiles[destPosition] = null;
                return;
            }
            if (newAutoTile.Type == AutoTileType.AutoTile4)
                tileSet.DefinedAutoTiles[destPosition] = new AutoTile4(newAutoTile);
            else if (newAutoTile.Type == AutoTileType.AutoTile5)
                tileSet.DefinedAutoTiles[destPosition] = new AutoTile5(newAutoTile);
            tileSet.DefinedAutoTiles[destPosition].TileSetIndex = (short) tileSet.Index;
        }

        public void Undo()
        {
            var tileSet = ((TileSet)BaseObject.Objects[destTileSetID]);
            if (oldAutoTile == null)
            {
                tileSet.DefinedAutoTiles[destPosition] = null;
                return;
            }
            if (oldAutoTile.Type == AutoTileType.AutoTile4)
                tileSet.DefinedAutoTiles[destPosition] = new AutoTile4(oldAutoTile);
            else if (oldAutoTile.Type == AutoTileType.AutoTile5)
                tileSet.DefinedAutoTiles[destPosition] = new AutoTile5(oldAutoTile);
            tileSet.DefinedAutoTiles[destPosition].TileSetIndex = (short) tileSet.Index;
        }

        public string GetDescription()
        {
            return "Change Auto Tile At : " + destPosition.X + ", " + destPosition.Y;
        }

        public string GetName()
        {
            return "Change Auto Tile";
        }
    }
}